package com.magupe.push.client.handler;

import java.io.File;
import java.io.RandomAccessFile;

import com.magupe.push.common.protocol.request.FileRequestPacket;
import com.magupe.push.common.protocol.response.FileResponsePacket;
import com.magupe.push.common.utils.Constants;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class FileResponseHandler extends SimpleChannelInboundHandler<FileResponsePacket>{
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FileResponsePacket packet) throws Exception {
		FileRequestPacket request = new FileRequestPacket();
		request.setContentId(packet.getContentId());
		request.setSecret(packet.getSecret());
		request.setUserId(packet.getUserId());
		request.setMsgId(packet.getMsgId());
		request.setSource(packet.getSource());
		request.setPath(packet.getPath());
		
		long startPos = packet.getStartPos();
		if(startPos != -1) {
			RandomAccessFile randomAccessFile = new RandomAccessFile(new File(request.getPath()), "rw");
			randomAccessFile.seek(startPos); // 将服务端返回的数据设置此次读操作，文件的起始偏移量
			
			long d_value = randomAccessFile.length() - startPos;
			byte[] bytes = new byte[Constants.LAST_LENGTH]; 
			if (d_value < Constants.LAST_LENGTH) { // 最后一块数据块，长度不足Constants.LAST_LENGTH
				bytes = new byte[(int) d_value]; 
			}
			
			int byteRead;
			if ((byteRead = randomAccessFile.read(bytes)) != -1 && (randomAccessFile.length() - startPos) > 0) {
				request.setEndPos(byteRead);
				request.setBytes(bytes);
            }
			
			randomAccessFile.close();
			ctx.channel().writeAndFlush(request);
		} else {
			ctx.channel().close();
		}
	}
	

}
